/*调用open系统调用打开一个叫做test.txt的文件（如果不存在则会创建该文件），然后调用write（）系统调用
 * 将字符串MSG_STR写入该文件中，之后调用read（）系统调用读出改文件里的内容			*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>

#define	TRUE	1
#define ERROR	-1

#define	MSG_STR	"Hello World!\n"
#define	BUFSIZE	1024

int main(int argc, char **argv)
{
	int fd = -1 ;
	
	int rv = -1 ;

	char file_name[] = "test.txt" ;

	char buf[BUFSIZE] ;

	fd = open(file_name, O_RDWR|O_CREAT|O_TRUNC, 0666) ;			//open file

	if(fd < 0)
	{	
		printf("open %s failed: %s", file_name, strerror(errno) ) ;	
		return ERROR ;
	}

	printf("open %s succeful, file descriptor %d\n", file_name, fd) ;

	rv = write(fd, MSG_STR, strlen(MSG_STR)) ;					//write file
	if(rv < 0)
	{
		perror("write file failed!\n") ;
		goto cleanup ;
	}
	
	
	memset(buf, 0, sizeof(buf)) ;
	lseek(fd, 0, SEEK_SET) ;


	rv = read(fd, buf, sizeof(buf)) ;						//read file
	if(rv < 0)				
	{
	
		perror("read file failed!\n") ;
		goto cleanup ;
	}
	
	printf("read %d byte from file: %s", rv, buf) ;

	write(STDOUT_FILENO, buf, strlen(buf)) ;

	fputs(buf, stdout) ;

	fprintf(stdout,"read %d byte from file %s", rv, buf) ;



	struct	stat	stbuf ;								//cat file information
	stat("test.txt", &stbuf) ;
	printf("File Mode: %o Real Size:%luB, Space Size:%luB\n",stbuf.st_mode, stbuf.st_size,
	stbuf.st_blksize) ;

	fstat(fd, &stbuf) ;
	printf("File Mode: %o Real Size:%luB, Space Size:%luB\n",stbuf.st_mode, stbuf.st_size,
	stbuf.st_blksize) ;


	if(access(file_name, F_OK) != 0)						//test file permission 
	{
		printf("%s is not exist\n", file_name) ;
	}
	else
		printf("%s is exist\n", file_name) ;




	


cleanup:

	close(fd) ;


	return 0 ;
}
